package main

import (
	"net"
	"time"
)

type Client struct {
	addr *net.UDPAddr
	time_sec int64
}

var clients map[string]Client

func Serve(sfd *net.UDPConn,cliaddr *net.UDPAddr, buf []byte){
	for url,cli :=  range clients {
		if (url != cliaddr.String()) {
			if (time.Now().Unix() - cli.time_sec > 60*5) {
				delete(clients,url)
				continue
			}
			sfd.WriteTo(buf,cli.addr)
		}
	}
}

func main() {
	println(time.Now().Unix())
	clients  = make(map[string]Client)
	println("main")
	socket, err := net.ListenUDP("udp4", &net.UDPAddr{
		IP:   net.IPv4(0, 0, 0, 0),
		Port: 8080,
    })
    if err != nil {
		println("listen error!")
        return
    }
    defer socket.Close()

	buf := make([]byte,10*1024)
	for {
		read, remoteAddr, err := socket.ReadFromUDP(buf)
		if err != nil {
			println("read from udp error !")
			continue
		}

		cli := Client{addr:remoteAddr,time_sec:time.Now().Unix()}
		clients[remoteAddr.String()] = cli
		go Serve(socket,remoteAddr,buf[:read])
	}
}


















